//
//  WeightRecordCell.m
//  WeightMaster
//
//  Created by sungeo on 15/8/20.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WeightRecordCell.h"
#import "WMModels.h"
#import "BDFoundation.h"
#import "UIColor+WeightMaster.h"
#import <EXTScope.h>
#import <Masonry.h>
#import <objc/runtime.h>

const float ProfileImageRadius = 15;
const float ValueViewRadius = 3;
const float ValueLabelHeight = 20;
const float BottomGapToContentView = 4;

const void * AssociatedCell = "AssociatedCellKey";

@interface WeightRecordCell (){
    float _maxValueViewHeight;
    __weak CALayer * _imageCircleLayer;
    
    __weak id _clickedlistener;
    SEL _clickedSelector;
}

@end

@implementation WeightRecordCell

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _maxValueViewHeight = MAXFLOAT;
        [self createSubViews];
    }
    
    return self;
}

- (instancetype)initWithWeight:(WMWeight *)weight ratio:(float)ratio{
    if (self = [self initWithFrame:CGRectZero]) {
        _weight = weight;
        _ratio = ratio;
    }
    
    return self;
}

- (void)createSubViews{
    @weakify(self);
    
    _profileImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:_profileImageView];
    [_profileImageView mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.centerX.equalTo(self.mas_centerX);
        maker.bottom.equalTo(self.mas_bottom).offset(- BottomGapToContentView);
        maker.width.equalTo(@(ProfileImageRadius * 2));
        maker.height.equalTo(_profileImageView.mas_width);
    }];
    _profileImageView.clipsToBounds = YES;
    _profileImageView.layer.cornerRadius = ProfileImageRadius;
    [_profileImageView addAction:@selector(imageClicked:) target:self];
    
    objc_setAssociatedObject(_profileImageView, AssociatedCell, self, OBJC_ASSOCIATION_ASSIGN);

    _valueLabel = [[UILabel alloc] init];
    _valueLabel.textAlignment = NSTextAlignmentCenter;
    _valueLabel.textColor = [UIColor lightGrayColor];
    _valueLabel.font = [UIFont systemFontOfSize:14.0];
    [self.contentView addSubview:_valueLabel];
    [_valueLabel mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.centerX.equalTo(self.mas_centerX);
        maker.bottom.equalTo(_profileImageView.mas_top);
        maker.width.equalTo(self.mas_width);
        maker.height.equalTo(@(ValueLabelHeight));
    }];
    
    _dateLabel = [[UILabel alloc] init];
    _dateLabel.textAlignment = NSTextAlignmentCenter;
    _dateLabel.textColor = [UIColor darkGrayColor];
    _dateLabel.font = [UIFont systemFontOfSize:14.0];
    [self.contentView addSubview:_dateLabel];
    [_dateLabel mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.centerX.equalTo(self.mas_centerX);
        maker.top.equalTo(self.mas_top);
        maker.width.equalTo(self.mas_width);
        maker.height.equalTo(@(1));
    }];

    _valueView = [[UIView alloc] init];
    _valueView.backgroundColor = [UIColor mainColor];
    [self.contentView addSubview:_valueView];
    [_valueView mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.centerX.equalTo(self.mas_centerX);
        maker.width.equalTo(@(1));
        maker.bottom.equalTo(_valueLabel.mas_top);
        maker.height.equalTo(@(1));
    }];
    _valueView.clipsToBounds = YES;
    _valueView.layer.cornerRadius = ValueViewRadius;
    
}

- (void)refreshWithSelectedState:(BOOL)selected{
    UIImage * image = [_weight profileImage];
    _profileImageView.image = image ? image : _moodImage;
    _valueLabel.text = [WMHelper stringValueForWeight:_weight.value withUnit:[WMAppSetting sharedInstance].weightUnit];
    
    @weakify(self);
    
    float dateLabelHeight = 0;
    if (_shouldShowDate) {
        [_dateLabel mas_remakeConstraints:^(MASConstraintMaker * maker){
            @strongify(self);
            maker.centerX.equalTo(self.mas_centerX);
            maker.top.equalTo(self.mas_top);
            maker.width.equalTo(self.mas_width);
            maker.height.equalTo(@(ValueLabelHeight));
        }];
        
        _dateLabel.text = [_weight monthAndDayString];
        dateLabelHeight = ValueLabelHeight;
    }
    
    _maxValueViewHeight = self.contentView.bounds.size.height;
    _maxValueViewHeight -= ProfileImageRadius * 2;
    _maxValueViewHeight -= ValueLabelHeight;
    _maxValueViewHeight -= dateLabelHeight;
    _maxValueViewHeight -= BottomGapToContentView;
    
    // 保证一定高度作为起始高度，避免高度为零的情况，体重差异在剩余的高度中体现
    const float AdjustValue = _maxValueViewHeight * 0.3;
    float height = AdjustValue + (_maxValueViewHeight - AdjustValue) * _ratio;

    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:.7 animations:^{
            [_valueView mas_remakeConstraints:^(MASConstraintMaker * maker){
                @strongify(self);
                maker.centerX.equalTo(self.mas_centerX);
                maker.width.equalTo(@(ValueViewRadius * 2));
                maker.bottom.equalTo(_valueLabel.mas_top);
                maker.height.equalTo(@(height));
            }];
            
            [self updateConstraintsIfNeeded];
            [self layoutIfNeeded];
        }];
    });
    
    [self changeSelectedState:selected];
}

- (void)addProfileImageClickedListener:(id)listener action:(SEL)selector{
    _clickedlistener = listener;
    _clickedSelector = selector;
}

- (void)imageClicked:(id)sender{
    if (_clickedlistener && _clickedSelector) {
        [_clickedlistener performSelector:_clickedSelector withObject:self];
    }
}

- (void)changeSelectedState:(BOOL)selected{
    if (selected) {
        _valueLabel.textColor = [UIColor mainColor];
        
        // 画光圈
        if(_imageCircleLayer == nil){
            CGFloat borderWidth = 1;
            CGFloat radius = _profileImageView.bounds.size.width / 2 + borderWidth + 1;// 留一像素空隙
            UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:_profileImageView.center radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];
            CAShapeLayer * layer = [CAShapeLayer layer];
            layer.strokeColor = [UIColor mainColor].CGColor;
            layer.lineWidth = borderWidth;
            layer.fillColor = [UIColor clearColor].CGColor;
            layer.path = path.CGPath;
            [self.contentView.layer addSublayer:layer];
            _imageCircleLayer = layer;
//            NSLog(@"添加光圈：%@", _weight.value);
        }
    }else{
        _valueLabel.textColor = [UIColor lightGrayColor];
        
        // 移除光圈
        if (_imageCircleLayer) {
            [_imageCircleLayer removeFromSuperlayer];
            _imageCircleLayer = nil;
//            NSLog(@"移除光圈：%@", _weight.value);
        }
    }
}

+ (BOOL)requiresConstraintBasedLayout{
    return YES;
}

@end
